package xiaopiya.robot.handler.translate;

import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jivesoftware.smack.XMPPException;

import xiaopiya.robot.handler.help.GoogleUser;

/**
 * @author Ray (ayufox@gmail.com)
 * @version 0.1
 */
public class GoogleTalkTranslateService
{
	private final static Log LOG = LogFactory
			.getLog(GoogleTalkTranslateService.class);

	private BlockingQueue<GoogleTranslater> translaters;

	private List<GoogleUser> googleUsers;

	public void setGoogleUsers(List<GoogleUser> googleUsers)
	{
		this.googleUsers = googleUsers;
	}

	public void init()
	{
		if (this.googleUsers == null)
		{
			throw new IllegalStateException("googleUsers can't be null");
		}

		this.translaters = new ArrayBlockingQueue<GoogleTranslater>(
				this.googleUsers.size());
		new Thread()
		{
			public void run()
			{
				for (GoogleUser user : googleUsers)
				{
					try
					{
						GoogleTranslater translater = new GoogleTranslater(user
								.getUsername(), user.getPassword());
						translater.start();
						translaters.add(translater);
					} catch (Throwable t)
					{
						LOG.error(
								"error when create google translater instance",
								t);
					}
				}
			}
		}.start();
	}

	public void destroy()
	{
		while (!this.translaters.isEmpty())
		{
			try
			{
				GoogleTranslater translater = this.translaters.poll();
				translater.shutdown();
			} catch (Throwable t)
			{
				LOG.error("Error when shutdown googletranslater", t);
			}
		}
	}

	/* (non-Javadoc)
	 * @see xiaopiya.robot.handler.translate.ITranslateService#translate(java.lang.String)
	 */
	public String translate(String source)
	{
		GoogleTranslater translater = null;
		try
		{
			translater = this.translaters.poll(2,
					TimeUnit.SECONDS);
			if (translater == null)
			{
				return "翻译服务繁忙，请稍候重试";
			}
			String result = translater.translate(source);
			if (result == null)
			{
				return "连接翻译服务错误，请重试";
			} else
			{
				return result;
			}
		} catch (InterruptedException e)
		{
			return "翻译服务繁忙，请选择其他服务";
		} catch (XMPPException e)
		{
			return "连接翻译服务错误，请重试";
		}
		finally
		{
			if (translater != null)
			{
				this.translaters.add(translater);
			}
		}
	}

}
